package rpcx

import (
	"context"
	"gogame/pb"
	"sync"
)

/*对pb.ApiRequest进行的二次封装*/

type Request struct {
	*pb.ApiRequest
	Ctx context.Context
}

func NewRequest(ctx context.Context, apiRequest *pb.ApiRequest) *Request {
	_request := RequestPool.Get()
	_request.ApiRequest = apiRequest
	_request.Ctx = ctx

	return _request
}

// Reset 资源重置
func (r *Request) Reset() {
	r.ApiRequest = nil
	r.Ctx = nil
}

/*
 ---------- pool 减少GC ----------
*/
type requestPool struct {
	pool *sync.Pool
}

var RequestPool = &requestPool{
	pool: &sync.Pool{
		New: func() any {
			return &Request{}
		},
	},
}

func (p *requestPool) Get() *Request {
	return p.pool.Get().(*Request)
}

func (p *requestPool) Put(request *Request) {
	request.Reset()
	p.pool.Put(request)
}

// PutRequest 资源回收
func PutRequest(request *Request) {
	RequestPool.Put(request)
}
